<template>
  <div>
    <div class="page-form">
      <el-select
        v-hasRole="['admin']"
        v-model="queryParams.schoolId"
        placeholder="全部学校"
        clearable
        @change="handleSearch"
      >
        <el-option
          v-for="dict in xxlb"
          :key="dict.id"
          :label="dict.schoolName"
          :value="dict.id"
        />
      </el-select>
      <el-select
        v-model="queryParams.reviewSubject"
        placeholder="管理科目"
        clearable
        @change="handleSearch"
      >
        <el-option
          v-for="dict in kslb"
          :key="dict.id"
          :label="dict.name"
          :value="dict.name"
        />
      </el-select>
      <el-select
        v-model="queryParams.role"
        placeholder="选择角色"
        clearable
        @change="handleSearch"
      >
        <el-option
          v-for="dict in roleList"
          :key="dict.roleId"
          :label="dict.roleName"
          :value="dict.roleId"
        />
      </el-select>
      <el-input
        v-model="queryParams.phone"
        placeholder="手机号&账号"
        clearable
        @input="handleSearch"
      />
      <el-input
        v-model="queryParams.teacherName"
        placeholder="教师姓名"
        clearable
        @input="handleSearch"
      />
    </div>
    <el-table
      stripe
      border
      ref="tableList"
      v-loading="loading"
      :data="tableData"
      style="width: 100%"
      @selection-change="handleSelectionChange"
      row-key="userId"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
        :reserve-selection="true"
      />
      <el-table-column label="序号" type="index" align="center">
        <template slot-scope="scope">
          <span>{{
            (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="姓名"
        align="center"
        prop="teacherName"
        :show-overflow-tooltip="true"
        width="140"
      />
      <el-table-column
        label="所属学校"
        align="center"
        prop="schoolName"
        :show-overflow-tooltip="true"
        width="220"
      />
      <el-table-column
        label="角色"
        align="center"
        :show-overflow-tooltip="true"
        width="180"
      >
        <template slot-scope="scope">
          {{ roleFilter(scope.row.role) }}
        </template>
      </el-table-column>
      <el-table-column
        label="手机号&账号"
        align="center"
        prop="phone"
        width="220"
      />
      <el-table-column label="管理科目" align="center">
        <template slot-scope="scope">
          <km-tag :option="scope.row.reviewSubject" separator=","></km-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="120"
      >
        <template slot-scope="scope">
          <el-link type="primary" @click="edit(scope.row)">编辑</el-link>
          <el-link
            type="danger"
            v-if="$auth.hasRole('admin')"
            :disabled="!scanStatus"

            @click="del(scope.row.id)"
            >删除</el-link
          >
        </template>
      </el-table-column>
    </el-table>

    <div class="page-bottom">
      <div class="sel-box">
        <p>
          已选 <span>{{ ids.length }}</span> 项 / 共 {{ total }} 项
        </p>
        <el-button type="primary" @click="edit(false)" v-hasRole="['admin']"
          >添加教师</el-button
        >
        <el-button
          type="primary"
          @click="upload.open = true"
          v-hasRole="['admin']"
          >批量上传</el-button
        >
        <el-button
          type="primary"
          @click="qxopen"
          :loading="loading"
          v-hasRole="['admin']"
          >权限管理</el-button
        >
        <el-button
          type="danger"
          :disabled="multiple || !scanStatus"
          @click="del(false)"
          v-hasRole="['admin']"
          >批量删除</el-button
        >
      </div>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <el-dialog
      ref="editDialog"
      class="editKmVisible"
      title="创建/编辑教师"
      :visible.sync="editKmVisible"
      width="436px"
      :before-close="beforeClose"
    >
      <el-form
        ref="editForm"
        :model="editForm"
        :rules="rules"
        label-position="left"
        label-width="140px"
      >
        <el-form-item label="学校名称" prop="schoolId">
          <el-select
            v-model="editForm.schoolId"
            filterable
            @change="schoolChange"
            :disabled="!$auth.hasRole('admin')"
          >
            <el-option
              v-for="dict in xxlb"
              :key="dict.schoolId"
              :label="dict.schoolName"
              :value="dict.schoolId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="教师姓名" prop="teacherName">
          <el-input
            v-model="editForm.teacherName"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号&账号" prop="phone">
          <el-input v-model="editForm.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item v-if="!editForm.id" label="密码" prop="password">
          <el-input
            v-model="editForm.password"
            type="password"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="editForm.role" multiple>
            <el-option
              v-for="dict in roleList"
              :key="dict.roleId"
              :label="dict.roleName"
              :value="dict.roleId.toString()"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="评阅&管理科目" prop="reviewSubject">
          <el-select v-model="editForm.reviewSubject" multiple>
            <el-option
              v-for="dict in xklb"
              :key="dict.subjectId"
              :label="dict.examSubjectName"
              :value="dict.examSubjectName"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">返 回</el-button>
        <el-button type="primary" @click="editSubmit" :loading="loading"
          >保 存</el-button
        >
      </div>
    </el-dialog>

    <el-dialog
      title="批量上传-评阅教师"
      :visible.sync="upload.open"
      :close-on-click-modal="false"
      width="400px"
      append-to-body
    >
    <span style="display:block;padding-bottom:15px;font-size:12px;color:red;">注意:重复导入时，原有数据将被新导入数据覆盖</span>
    <div style="display:flex;align-items:center;">
        <div style="margin-bottom:15px;margin-right:15px;">导入学校</div>
        <el-select
        v-model="upload.deptId"
        filterable
        style="margin-bottom: 15px"
        @change="getExamSchoolId"
        ref="schoolSelect"
      >
        <el-option
          v-for="dict in xxlb"
          :key="dict.schoolId"
          :label="dict.schoolName"
          :value="dict.schoolId"
        />
      </el-select>
    </div>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        action=""
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        :http-request="customUpload"
        drag
        @dragover.native="handleDragOver"
        @drop.native="handleDrop" 
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
            >下载模板</el-link
          >
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="submitFileForm"
          :loading="upload.isUploading"
          >确 定</el-button
        >
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="权限管理" :visible.sync="qxglVisible" width="1100px">
      <span>维护当前考试内各角色的权限，修改完成后仅对当前考试生效。</span>

      <el-table
        :data="qxData"
        border
        style="margin-top: 15px"
        v-if="qxData.length > 0"
      >
        <el-table-column
          width="120"
          label="角色"
          prop="roleName"
        ></el-table-column>
        <template v-for="(item, i) in qxData[0].tableData">
          <el-table-column
            :key="item.id"
            :label="item.label"
            v-if="item.label != '成绩管理'"
          >
            <template slot-scope="scope">
              <div v-for="v in scope.row.tableData[i].children" :key="v.id">
                <el-checkbox v-model="scope.row.checked" :label="v.id">{{
                  v.label
                }}</el-checkbox>
              </div>
            </template>
          </el-table-column></template
        >
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="qxglbc">确 定</el-button>
        <el-button @click="qxglVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { debounce } from "lodash";
import {
  examTeacherList,
  examTeacherAdd,
  examTeacherEdit,
  examTeacherDel,
  templatemenu,
  templatemenulist,
  uploadImportTeacher
} from "@/api/xmgl/pyjsgl";
import { scanStatus } from "@/api/jcgl/jsgl";

import { schoolsubjectlist, checkPassword } from "@/api/common";
import { getToken } from "@/utils/auth";
import { schoollist } from "@/api/xmgl/csxx";
import { listRole } from "@/api/system/role";
import { treeselect } from "@/api/system/menu";
import { subjectpage } from "@/api/xmgl/ksgl";
import { blobValidate } from "@/utils/exam";
import { saveAs } from 'file-saver'

export default {
  props: {
    xmxx: {},
  },
  data() {
    return {
      loading: false,

      ids: [],

      total: 0,
      tableData: [],

      multiple: true,

      queryParams: {
        pageNum: 1,
        pageSize: 15,
      },
      editKmVisible: false,
      editForm: {
        schoolId: "",
        teacherName: "",
        phone: "",
        password: "",
        role: [],
        reviewSubject: [],
      },
      rules: {
        schoolId: [
          { required: true, message: "学校名称不能为空", trigger: "change" },
        ],
        grade: [{ required: true, message: "年级不能为空", trigger: "change" }],
        teacherName: [
          { required: true, message: "教师姓名不能为空", trigger: "change" },
        ],
        phone: [
          { required: true, message: "手机号&账号不能为空", trigger: "change" },
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "change" },
        ],
        role: [{ required: true, message: "角色不能为空", trigger: "change" }],
        reviewSubject: [
          {
            required: true,
            message: "评阅&管理科目不能为空",
            trigger: "change",
          },
        ],
      },

      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 学校
        deptId: "",
        examSchoolId: "",
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/exam/teacher/import",
      },

      xxlb: [],
      jslb: [],
      roleList: [],
      xklb: [],

      qxglVisible: false,
      qxData: [],

      // 菜单列表
      menuOptions: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label",
      },

      kslb:[],
      scanStatus: true,

    };
  },
  created() {
    scanStatus({ examId: this.xmxx.id }).then((res) => {
      this.scanStatus = res.data;
    })

    subjectpage({ pageNum: 1, pageSize: 9999, examId: this.xmxx.id }).then(
      (response) => {
        this.kslb = response.rows;
      }
    );

    this.loading = true;
    schoollist({ pageNum: 1, pageSize: 9999, examId: this.xmxx.id }).then(
      (res) => {
        this.xxlb = res.rows;

        if (!this.$auth.hasRole("admin")) {
          this.queryParams.schoolId = this.xxlb.filter((item) => {
            return item.schoolId == this.$store.state.user.deptId;
          })[0].id;
        }

        this.getList();
      }
    );
    listRole({ pageNum: 1, pageSize: 9999 }).then((res) => {
      this.roleList = res.rows.filter((item) => {
        return item.roleKey != "admin";
      });
      if (this.$auth.hasRole("admin")) {
        // 加载权限树
        treeselect().then((res) => {
          let qxData = JSON.parse(JSON.stringify(this.roleList));
          qxData = qxData.filter((item) => {
            return item.roleKey.indexOf("reviewing:teachers:") != -1;
          });
          let data = res.data.filter((item) => {
            return item.label == "评阅教师权限";
          })[0].children;

          qxData = qxData.map((item) => {
            return {
              ...item,
              tableData: data,
              checked: [],
            };
          });
          this.qxData = qxData;
        });
      }
    });
  },
  methods: {
    getList() {
      this.loading = true;
      this.tableData = [];
      examTeacherList({ ...this.queryParams, examId: this.xmxx.id })
        .then((response) => {
          this.tableData = response.rows;
          this.total = response.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.multiple = !selection.length;
    },
    debouncedSearch: debounce(function () {
      this.queryParams.pageNum = 1;
      this.getList();
    }, 500),
    handleSearch() {
      this.debouncedSearch();
    },
    edit(row) {
      if (row) {
        this.editForm.id = row.id;
        this.editForm.schoolId = this.xxlb.filter((item) => {
          return item.id == row.schoolId;
        })[0].schoolId;
        this.editForm.teacherName = row.teacherName;
        this.editForm.phone = row.phone;
        this.editForm.role = row.role.split(",");
        this.editForm.reviewSubject = row.reviewSubject
          ? row.reviewSubject.split(",")
          : [];
        this.schoolChange();
      }

      this.editKmVisible = true;
    },

    beforeClose(done) {
      this.editForm = {
        schoolId: "",
        teacherName: "",
        phone: "",
        password: "",
        role: [],
        reviewSubject: [],
      };
      this.$nextTick(() => {
        this.$refs.editForm.clearValidate();
        done();
      });
    },
    handleClose() {
      this.beforeClose(() => {
        this.editKmVisible = false;
      });
    },

    editSubmit() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          let req;
          if (this.editForm.id) {
            req = examTeacherEdit;
          } else {
            req = examTeacherAdd;
          }
          let data = {
            ...this.editForm,
            examId: this.xmxx.id,
          };

          data.schoolId = this.xxlb.filter((item) => {
            return item.schoolId == data.schoolId;
          })[0].id;
          data.role = data.role.join(",");
          data.reviewSubject = data.reviewSubject.join(",");
          req(data)
            .then((res) => {
              this.$modal.msgSuccess("操作成功");
              this.handleClose();
              this.getList();
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },
    del(id) {
      this.$prompt(
        "删除评阅教师后，可能造成评阅教师不能登录评阅，请输入管理员密码以进行下步操作!",
        "删除评阅教师",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          inputPlaceholder: "请输入管理员密码",
          inputType: "password",
          inputValidator: (value) => {
            if (!value) {
              return "请输入密码";
            } else {
              return true;
            }
          },
        }
      )
        .then(({ value }) => {
          checkPassword({
            password: value,
            schoolId: this.$store.state.user.deptId,
          }).then((res) => {
            examTeacherDel(id ? id : this.ids).then((res) => {
              this.$modal.msgSuccess("操作成功");
              this.$refs.tableList.clearSelection();
              this.ids = [];
              this.getList();
            });
          });
        })
        .catch(() => {});
    },

    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      window.open(
        "https://bs-exam-bucket.oss-cn-beijing.aliyuncs.com/dev/bsta/exam/uploadPath/upload/template/teacher_template.xlsx"
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.deptId = "";
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.allDeptList = null;
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      if (!this.upload.deptId) {
        this.$modal.alertError("请选择导入学校");
        return;
      }
      this.$refs.upload.submit();
    },

    schoolChange() {
      let examSchoolId = this.xxlb.filter((item) => {
        return item.schoolId == this.editForm.schoolId;
      })[0].id;
      schoolsubjectlist({
        examId: this.xmxx.id,
        examSchoolId: examSchoolId,
      }).then((res) => {
        this.xklb = res.rows;
      });
    },

    getExamSchoolId(value) {
      this.upload.examSchoolId = this.xxlb.filter((item) => {
        return item.schoolId == value;
      })[0].id;
    },

    roleFilter(role) {
      let roleArr = role.split(",");
      return this.roleList
        .filter((item) => {
          return roleArr.indexOf(item.roleId.toString()) != -1;
        })
        .map((item) => {
          return item.roleName;
        })
        .join(",");
    },

    qxopen() {
      this.loading = true;
      templatemenulist({ examId: this.xmxx.id })
        .then((res) => {
          this.qxglVisible = true;
          let qxData = JSON.parse(JSON.stringify(this.qxData));

          qxData.map((item) => {
            item.checked = [];
            res.rows.map((v) => {
              if (item.roleId == v.roleId) {
                item.checked.push(v.menuId);
              }
            });
          });

          this.qxData = qxData;
        })
        .finally(() => {
          this.loading = false;
        });
    },

    qxglbc() {
      this.loading = true;

      let arr = this.qxData.filter((item) => {
        return item.checked && item.checked.length > 0;
      });

      let data = [];
      arr.map((item) => {
        item.checked.map((v) => {
          data.push({
            roleId: item.roleId,
            menuId: v,
            examId: this.xmxx.id,
          });
        });
      });

      templatemenu(data)
        .then((res) => {
          this.qxglVisible = false;
          this.$modal.msgSuccess("操作成功");
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 3. 拖拽经过上传区域时，关闭el-select下拉框
    handleDragOver() {
      this.closeSelectDropdown();
    },
    // 4. 拖拽释放到上传区域时，关闭el-select下拉框
    handleDrop() {
      this.closeSelectDropdown();
    },
    // 封装关闭下拉框的方法
    closeSelectDropdown() {
      // 通过ref获取el-select实例，调用其内部方法关闭下拉框
      if (this.$refs.schoolSelect) {
        this.$refs.schoolSelect.visible = false; // 强制关闭下拉框
      }
    },
    customUpload(option){
      this.upload.isUploading = true;
        let data={
          file:option.file
        }
        uploadImportTeacher(data,this.upload.deptId,this.xmxx.id,this.upload.examSchoolId).then(res=>{
          console.info(res,'resssss')
          if(res&&res.data&&res.data.size!=0){
            // 直接使用response.data（已为blob类型）
            const blob = new Blob([res.data]);
            // 获取文件名
            const filename = "教师导入结果.xlsx";
            saveAs(blob, filename)
            this.upload.open = false;
            this.upload.deptId = "";
            this.upload.isUploading = false;
            this.$refs.upload.clearFiles();
            this.allDeptList = null;
            this.getList();
            this.$alert('失败原因及原始表格已下载，请修改后再重新导入', '导入失败!', {
              confirmButtonText: '确定',
               customClass: 'my-alert',
              callback: action => {}
            });
          }else{
            this.upload.open = false;
            this.upload.deptId = "";
            this.upload.isUploading = false;
            this.$refs.upload.clearFiles();
            this.$message({
              message: '导入成功！',
              duration:3000,
              type: 'success'
            });
            this.allDeptList = null;
            this.getList();
          }
        })
    },
  },
};
</script>

<style lang="scss" scoped>
.editKmVisible {
  .el-input,
  .el-cascader,
  .el-select {
    width: 240px;
  }
  .el-dialog__body{
    padding-top:0;
  }
}
</style>